package com.ytrsoft.io;

import com.ytrsoft.utils.Commands;

import java.io.*;
import java.nio.charset.Charset;

public class StreamRedirector extends Thread {

    private final OutputStream out;
    private final BufferedReader buffer;

    public StreamRedirector(InputStream in, OutputStream out) {
        this.out = out;
        Charset charset = Charset.forName(getDefaultEncoding());
        this.buffer = new BufferedReader(new InputStreamReader(in, charset));
    }

    @Override
    public void run() {
        try {
            char[] chars = new char[1024];
            while (buffer.read(chars, 0, chars.length) != -1) {
                String s = String.valueOf(chars);
                byte[] bytes = s.getBytes();
                out.write(bytes, 0, bytes.length);
                out.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getDefaultEncoding() {
        return Commands.isWindows() ? "GBK" : "UTF-8";
    }
}
